20230319
p5.js
Generative Art
View Source Code
let objSize = 0;
const objects = [];
const MAX = 12;
const OFFSET_NUM = 3;
// function keyPressed() {
// if (key === 's') {
// saveGif('p5art.gif', 3);
// }
// }
// function setup() {
// createCanvas(320, 320);
function setup() {
createCanvas(windowWidth, windowHeight);
frameRate(60);
objSize = height / MAX;
for (let y = -1; y < MAX + 1; y++) {
for (let x = -1; x < (width / objSize) + 1; x++) {
const offsetX = 0; //(objSize / OFFSET_NUM) * (y % OFFSET_NUM)
const offsetY = 0; //(objSize / OFFSET_NUM) * (x % OFFSET_NUM)
let obj;
let myType = abs((y * x) % 3);
// console.log('%d %d %d', x, y, myType)
switch (myType) {
case 0:
obj = new MyEllipse(
x * objSize + offsetX,
y * objSize + offsetY,
objSize,
objSize,
pastelColor()
);
break;
case 1:
obj = new MyRect(
x * objSize + offsetX,
y * objSize + offsetY,
objSize,
objSize,
pastelColor()
);
break;
case 2:
obj = new MyArc(
x * objSize + offsetX,
y * objSize + offsetY,
objSize,
objSize,
pastelColor()
);
break;
}
objects.push(obj);
}
}
}
function pastelColor() {
return color(random(64, 255), random(64, 255), random(64, 255));
}
function draw() {
background(0, 0, 0, 10);
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
obj.move();
}
for (let i = 0; i < objects.length; i++) {
const obj = objects[i];
obj.draw();
}
}
class AbstractObject {
constructor(x, y, w, h, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
this.amount = 1;
this.skip = 1;
}
move() {
if (this.amount < 1) {
this.amount += this.skip * (deltaTime / 2000);
}
this.dist = dist(this.x, this.y, mouseX, mouseY);
if (this.dist < this.w) {
this.amount = 0;
}
this.amount = constrain(this.amount, 0, 1);
}
draw() {}
calcSizeBy() {
const sizeBy = constrain(map(this.dist, 0, this.w * 3, 0, 1), 0, 1);
return lerp(0, sizeBy, this.amount);
}
setColor(sizeBy) {
noStroke();
// fill(255 * sizeBy, 255 * sizeBy, 255, 255 * sizeBy);
fill(lerpColor(this.color, color(255, 255, 255), sizeBy));
// fill(red(this.color) * sizeBy, green(this.color) * sizeBy, blue(this.color) * sizeBy, 255);
}
}
class MyEllipse extends AbstractObject {
draw() {
let sizeBy = this.calcSizeBy();
this.setColor(sizeBy);
ellipse(this.x, this.y, this.w * sizeBy, this.h * sizeBy);
// this.debugText(this.amount)
}
// debugText(message) {
// textSize(9);
// // console.log(this.color)
// fill(255,0,0);
// text(message, this.x - (this.w / 2), this.y);
// }
}
class MyRect extends AbstractObject {
draw() {
let sizeBy = this.calcSizeBy();
this.setColor(sizeBy);
push();
// translate(width/2, height/2);
translate(this.x, this.y)
rotate(radians(180 * sizeBy));
rect(
- (this.w * sizeBy) / 2,
- (this.h * sizeBy) / 2,
this.w * sizeBy,
this.h * sizeBy
);
pop();
}
}
class MyArc extends AbstractObject {
draw() {
let sizeBy = this.calcSizeBy();
this.setColor(sizeBy);
arc(this.x, this.y, this.w, this.h, 0, PI * 2 * sizeBy);
}
}